package com.xq.jltx.frescosimple.adapters;

import android.content.Context;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.image.QualityInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.xq.jltx.frescosimple.R;
import com.xq.jltx.frescosimple.display.DefaultDrawables;
import com.xq.jltx.frescosimple.display.FrescoDraweeView;
import com.xq.jltx.frescosimple.display.ImageLoadeInstrumented;
import com.xq.jltx.frescosimple.display.PerfListener;
import com.xq.jltx.frescosimple.utils.XqLog;


/**
 * @author jltxseo
 *         Created by junlintianxia on 2016年02月03日.
 */

public class FrescoGridViewAdapter extends ImageListAdapter<FrescoGridViewAdapter.ViewHolder>{

    private LayoutInflater inflater;
    private Context context;
    private PerfListener mPerfListener;
    private String[]  imageList;

    public FrescoGridViewAdapter(Context context, String[] imageList, ImagePipelineConfig imagePipelineConfig, PerfListener mPerfListener) {
        super(imageList, mPerfListener);
        Fresco.initialize(context, imagePipelineConfig);
        this.context = context;
        this.imageList = imageList;
        this.mPerfListener = mPerfListener;
        init();
    }

    public void init(){
        inflater = LayoutInflater.from(context);
    }

    @Override
    protected Class<ViewHolder> getViewClass() {
        return ViewHolder.class;
    }

    @Override
    protected ViewHolder createViewHolder() {
        final ViewHolder viewHolder = new ViewHolder();
        View view = inflater.inflate(R.layout.item_grid_image,null,false);
        viewHolder.frescoDraweeView = (FrescoDraweeView)view.findViewById(R.id.drawImg);
        viewHolder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
        /**
         *这里是一个坑，不同的DraweeView不能用同一个GenericDraweeHierarchy
         */
        GenericDraweeHierarchy displayCoverImgDH = new GenericDraweeHierarchyBuilder(context.getResources())
                .setPlaceholderImage(DefaultDrawables.sPlaceholderDrawable, ScalingUtils.ScaleType.CENTER_CROP)
                .setFailureImage(DefaultDrawables.sErrorDrawable,ScalingUtils.ScaleType.CENTER_CROP)
//                .setRoundingParams(RoundingParams.asCircle())
//                .setProgressBarImage(new ProgressBarDrawable())
                //这里设置下载进度条，通过这里可以将进度回调出去
/*                .setProgressBarImage(new Drawable() {
                    @Override
                    protected boolean onLevelChange(int level) {
                        int length = 100 * level / 10000;
                        XqLog.d("IIIII","进度=>"+level);
                        viewHolder.progressBar.setProgress(length);
                        return true;
                    }
                    @Override
                    public void draw(Canvas canvas) {

                    }

                    @Override
                    public void setAlpha(int i) {

                    }

                    @Override
                    public void setColorFilter(ColorFilter colorFilter) {

                    }

                    @Override
                    public int getOpacity() {
                        return 0;
                    }
                })*/
                .build();
        RoundingParams roundingParams = new RoundingParams();
        roundingParams.setCornersRadius(20);
        displayCoverImgDH.setRoundingParams(roundingParams);
        viewHolder.frescoDraweeView.setHierarchy(displayCoverImgDH);
        viewHolder.rootView = view;
        return viewHolder;
    }

    @Override
    protected void bind(final ViewHolder viewHolder, String uri) {
        //从服务器下载，或者本地获取的图片做些修改，比如在某个坐标统一加个网格什么的。你可以使用 Postprocessor
/*        Postprocessor redMeshPostprocessor = new BasePostprocessor() {
            @Override
            public String getName() {
                return "redMeshPostprocessor";
            }

            @Override
            public void process(Bitmap bitmap) {
                for (int x = 0; x < bitmap.getWidth(); x+=2) {
                    for (int y = 0; y < bitmap.getHeight(); y+=2) {
                        bitmap.setPixel(x, y, Color.RED);
                    }
                }
            }
        };*/
        ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri))
                //Fresco 多图加载之ResizeOptions，解决图片加载时卡顿现象
                .setResizeOptions(new ResizeOptions(200, 200))
                .setAutoRotateEnabled(true)   //自动旋转
                .setProgressiveRenderingEnabled(false)
//                .setPostprocessor(redMeshPostprocessor)
                .build();
        ControllerListener controllerListener =  new BaseControllerListener<ImageInfo>(){
            @Override
            public void onFinalImageSet(String id,  ImageInfo imageInfo,  Animatable animatable) {   //下载成功回调到这里
                XqLog.d("YYYYYY","onFinalImageSet"+id);
                if (imageInfo == null) {
                    return;
                }
//                viewHolder.progressBar.setVisibility(View.INVISIBLE);
                QualityInfo qualityInfo = imageInfo.getQualityInfo();
                XqLog.d("YYYYYY","Size.width:"+imageInfo.getWidth()+",Size.height:"+imageInfo.getHeight()+",Quality level:"+qualityInfo.getQuality()+",good enough:"+ qualityInfo.isOfGoodEnoughQuality()+", full quality:"+qualityInfo.isOfFullQuality());
            }

            @Override
            public void onFailure(String id, Throwable throwable) {   //下载失败回调到这里
                XqLog.d("YYYYYY","onFailure"+id);
//                viewHolder.progressBar.setVisibility(View.INVISIBLE);
                super.onFailure(id, throwable);
            }

            @Override
            public void onIntermediateImageFailed(String id, Throwable throwable) {
                super.onIntermediateImageFailed(id, throwable);
            }

            @Override
            public void onIntermediateImageSet(String id,  ImageInfo imageInfo) {
                super.onIntermediateImageSet(id, imageInfo);
            }

            @Override
            public void onRelease(String id) {   //取消下载或者滑动时释放下载回调到这里
                XqLog.d("YYYYYY","onRelease"+id);
//                viewHolder.progressBar.setVisibility(View.INVISIBLE);
                super.onRelease(id);
            }

            @Override
            public void onSubmit(String id, Object callerContext) {    //开始提交下载任务回调到这里
                XqLog.d("YYYYYY","onSubmit"+id);
//                viewHolder.progressBar.setVisibility(View.VISIBLE);
                super.onSubmit(id, callerContext);
            }
        };
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setImageRequest(imageRequest)
                .setOldController(viewHolder.frescoDraweeView.getController())
                .setControllerListener(controllerListener)
                .setAutoPlayAnimations(true)
                .build();
        viewHolder.frescoDraweeView.setController(draweeController);
    }

    @Override
    public void shutDown() {
        Fresco.shutDown();
    }

    public static class ViewHolder implements ImageLoadeInstrumented {
        public View rootView;
        public FrescoDraweeView frescoDraweeView;
        public ProgressBar progressBar;

        @Override
        public void initInstrumentation(String tag, PerfListener perfListener) {

        }

        @Override
        public View getItemRootView() {
            return rootView;
        }
    }
}
